package com.yz.crm.department.action;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yz.crm.db.model.BaseCompany;
import com.yz.crm.db.model.BaseDepartment;
import com.yz.crm.department.model.DeptTreeNode;
import com.yz.crm.department.service.DepartmentService;
import com.yz.crm.passport.model.SessionUser;
import com.yz.util.WebUtils;


@Controller
@RequestMapping("/department")
public class DeptTreeAction {

	@Resource
	private DepartmentService departmentService;
	
	/**
	 * 根据登录用户的所属公司取得部门树
	 * @param departmentId
	 * @return
	 */
	@RequestMapping(value="/tree")
	public String tree(HttpServletRequest request, ModelMap model){
		SessionUser user=WebUtils.getLoginUser(request);
		BaseCompany company=user.getCompany();
		model.put("company", company);
		return "/public/selectDept";
	}
	
	/**
	 * 加载下一级部门
	 * */
	@RequestMapping("/loadNext")
	@ResponseBody
	public List<DeptTreeNode> loadNext(String id,HttpServletRequest request, ModelMap modelMap){
		
		SessionUser user=WebUtils.getLoginUser(request);
		BaseCompany company=user.getCompany();
		
		List<BaseDepartment> deptList;
		if (company.getId().equals(id)){
			deptList = departmentService.listTopDepartment(id);
		}else{
			deptList = departmentService.listDirectSub(id);
		}
		
		List<DeptTreeNode> nodeList = new ArrayList<DeptTreeNode>();
		
		DeptTreeNode node;
		for (BaseDepartment c : deptList){
			node = new DeptTreeNode();
			node.setId(c.getId());
			node.setName(c.getName());
			node.setpId(c.getParentId());
			node.setParent(!departmentService.listDirectSub(c.getId()).isEmpty());
			nodeList.add(node);
		}
		return nodeList;
	}
}
